package com.jvxb.manage.livable.controller;

import com.baomidou.mybatisplus.core.conditions.Condition;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.jvxb.common.utils.CommonUtil;
import com.jvxb.common.web.RespMsg;
import com.jvxb.manage.livable.entity.AssetsAgentHost;
import com.jvxb.manage.livable.entity.AssetsInstance;
import com.jvxb.manage.livable.entity.SysRole;
import com.jvxb.manage.livable.service.AssetsAgentHostService;
import com.jvxb.manage.livable.service.AssetsInstanceService;
import com.jvxb.manage.livable.service.SysDictService;
import com.jvxb.modules.utils.FileStoreUtil;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.util.List;
import java.util.Map;

/**
 * @author jvxb
 * @since 2022-01-05
 */
@RestController
@RequestMapping("/agent/v1")
public class AgentHostController {

    @Autowired
    private AssetsAgentHostService assetsAgentHostService;
    @Autowired
    private AssetsInstanceService instanceService;
    @Autowired
    private SysDictService sysDictService;

    @GetMapping("one")
    public Object one(Integer id) {
        AssetsAgentHost assetsAgentHost = assetsAgentHostService.getById(id);
        return RespMsg.ok(assetsAgentHost);
    }

    @PostMapping("/add")
    public RespMsg add(@RequestBody AssetsAgentHost assetsAgentHost) {
        QueryWrapper wrapper = new QueryWrapper();
        wrapper.eq(AssetsAgentHost.HOST, assetsAgentHost.getHost());
        wrapper.eq(AssetsAgentHost.DBTYPE, assetsAgentHost.getDbType());
        if (assetsAgentHostService.count(wrapper) > 0) {
            return RespMsg.error("该机器已存在，ip=" + assetsAgentHost.getHost() + " 类型=" + assetsAgentHost.getDbType());
        }
        if (assetsAgentHost.getSupportInsNum() == null) {
            int supportInsNum = Integer.valueOf(sysDictService.getUniValueByGroupAndKey("agent_host", "default_support_ins_num", "8"));
            assetsAgentHost.setSupportInsNum(supportInsNum);
        }
        assetsAgentHostService.save(assetsAgentHost);
        return RespMsg.ok();
    }

    @PostMapping("/update")
    public RespMsg update(@RequestBody AssetsAgentHost assetsAgentHost) {
        assetsAgentHostService.saveOrUpdate(assetsAgentHost);
        return RespMsg.ok();
    }

    @PostMapping("/delete")
    public RespMsg delete(@RequestBody AssetsAgentHost assetsAgentHost) {
        AssetsAgentHost agentHost = assetsAgentHostService.getById(assetsAgentHost.getId());
        if (agentHost != null && instanceService.count(Condition.<AssetsInstance>create().eq(AssetsInstance.HOST, agentHost.getHost())) > 0) {
            throw new SecurityException(String.format("机器[%s]上残留有DB实例，请迁移或回收DB实例后再移除机器。"));
        }
        assetsAgentHostService.removeById(assetsAgentHost);
        return RespMsg.ok();
    }

    @PostMapping("batchDelete")
    public RespMsg<SysRole> batchDelete(@RequestBody Map param) {
        List<Integer> ids = (List<Integer>) param.get("ids");
        for (Integer id : ids) {
            assetsAgentHostService.removeById(id.longValue());
        }
        return RespMsg.ok();
    }

    @GetMapping("/list")
    public RespMsg list() {
        List<AssetsAgentHost> list = assetsAgentHostService.list(null);
        return RespMsg.ok(list);
    }


    @GetMapping("listPage")
    public RespMsg listPage(String host,
                            String dbType,
                            Integer isLock,
                            Integer isInit,
                            @RequestParam(defaultValue = "10") Integer size,
                            @RequestParam(defaultValue = "1") Integer current) {
        IPage<AssetsAgentHost> agentIPage = new Page<>(current, size);
        QueryWrapper wrapper = new QueryWrapper();
        wrapper.like(StringUtils.isNotEmpty(host), AssetsAgentHost.HOST, host);
        wrapper.like(StringUtils.isNotEmpty(dbType), AssetsAgentHost.DBTYPE, dbType);
        wrapper.like(CommonUtil.notNullOrEmpty(isLock), AssetsAgentHost.IS_LOCK, isLock);
        wrapper.like(CommonUtil.notNullOrEmpty(isInit), AssetsAgentHost.IS_INIT, isInit);
        wrapper.orderByDesc(AssetsAgentHost.CREATE_TIME);
        assetsAgentHostService.page(agentIPage, wrapper);
        return RespMsg.ok(agentIPage);
    }

    /**
     * 获取初始化版本
     */
    @GetMapping("/getInitVersion")
    public RespMsg getInitVersion() {
        String currentVersion = sysDictService.getUniValueByGroupAndKey("system", "agent_init_version", "v1.0.0");
        String initVersion = sysDictService.getUniValueByGroupAndKey(
                "system",
                "agent_init_cmd",
                "wget http://www.jvxb.com/agent/init/init_agent_" + currentVersion + ".sh -N -P /opt/tool && chmod 777 /opt/tool/init_agent_v1.0.0.sh && bash /opt/tool/init_agent_v1.0.0.sh");
        return RespMsg.ok(initVersion);
    }

    /**
     * 获取初始化shell
     * shellName: init_agent_v1.0.0.sh
     * shellContent:
     * echo "-----机器初始化开始执行-----"
     * initAgent
     * echo "-----机器初始化执行完毕-----"
     */
    @GetMapping("/init/{shellName}")
    public void getInitAgentShell(@PathVariable String shellName, HttpServletResponse response) throws Exception {
        //目标模板文件的位置
        String filePath = "links" + File.separator + shellName;
        //下载后显示的名字
        String downLownName = shellName;
        //开始下载
        FileStoreUtil.fileDownload(response, filePath, downLownName);
    }

    /**
     * 检查初始化状态
     */
    @PostMapping("/checkInitStatu")
    public RespMsg checkInitStatu(@RequestBody AssetsAgentHost assetsAgentHost) {
        try {
            AssetsAgentHost agentHost = assetsAgentHostService.getById(assetsAgentHost.getId());
            assetsAgentHostService.checkInitStatu(agentHost);
            return RespMsg.ok();
        } catch (Exception e) {
            return RespMsg.error("检测机器初始化状态异常，请联系平台值班查看。");
        }
    }

    /**
     * 检查初始化状态
     */
    @PostMapping("/changeLockState")
    public RespMsg changeLockState(@RequestBody Map param) {
        try {
            String host = (String) param.get("host");
            Integer isLock = (int) param.get("isLock");
            QueryWrapper wrapper = new QueryWrapper();
            wrapper.eq(AssetsAgentHost.HOST, host);
            List<AssetsAgentHost> agentHostList = assetsAgentHostService.list(wrapper);
            agentHostList.stream().forEach(e -> e.setIsLock(isLock));
            assetsAgentHostService.updateBatchById(agentHostList);
            return RespMsg.ok();
        } catch (Exception e) {
            return RespMsg.error("检测机器初始化状态异常，请联系平台值班查看。");
        }
    }
}
